import * as React from 'react';
import { SearchBox, Modal, DefaultButton, PrimaryButton, IconButton, Button } from 'office-ui-fabric-react';
import { Pivot, PivotItem, PivotLinkFormat } from 'office-ui-fabric-react/lib/Pivot';
import { ParagraphCard, ListContainer, AdvanceSearch } from '../../../components';
import { documentSearch, advanceDocumentSearch, documentGet } from '../../../services/documentAssistant';
import { insertHtmlAfterParagraph } from '../../../utils/WordUtil';
import { openDialog } from '../../../utils/WordDialog';

import './styles.less';

const typeOptions = [
  {
    key: '',
    text: '全部',
  },
  {
    key: '3',
    text: '段落',
  },
  {
    key: '2',
    text: '章节',
  },
  {
    key: '1',
    text: '全文',
  }
]
const sortOptions = [
  {
    key: 'new',
    text: '最相关',
  },
  {
    key: 'publish_time',
    text: '最新发布',
  }
]

export interface AppProps {
  onChange: any,
  page?: number,
  document: any,
}

export interface AppState {
  keyword?: string,
  showList?: boolean,
  searchType?: 'advance' | 'normal',
  type: '' | '1' | '2' | '3',
  sort?: any,
  page: number,
  pageSize: number,
  count: number,

  currentSort: any
  currentType: any
}

export default class DocumentResult extends React.Component<AppProps, AppState> {
  constructor(props, context) {
    super(props, context);
    this.state = {
      page: 1,
      pageSize: 10,
      count: 0,
      type: '', // 默认类型
      sort: {
        publish_time: { order: "desc" } // 默认排序
      },
      currentSort: sortOptions[0],
      currentType: typeOptions[0]
    };
  }

  handlePageChange = (page?: any) => {
    this.setState({
      page: page || 1,
    })
  }

  handleChange = () => {
    const { page, sort, type } = this.state
    const resolveData = {
      page,
      sort,
      type
    }
    // 待做 TODO
    console.info('回传数据', resolveData)
    this.props.onChange(resolveData)
  }

  // 最相关排序
  onSortChange = (sortItem) => {
    const { key } = sortItem
    const sort = {
      publish_time: {
        order: (key === 'publish_time') ? "desc" : 'asc'
      }
    }

    // 选择后文字改变
    this.setState({
      sort,
      currentSort: sortItem
    }, this.handleChange) // TODO ??
  }

  // 选择的类别 片段 章节 全文
  onTypeChange = (item) => {
    this.setState({
      currentType: item,
      type: item.key
    }, this.handleChange) // TODO ??
  }

  // 预览、插入按钮
  operateMenu = item => {
    let obj
    if (this.state.type === '1') {
      obj = {
        items: [
          {
            key: 'view',
            text: '预览',
            iconProps: {
              iconName: 'View',
            },
            onClick: () => {
              this.handleViewClick(item._id)
            }
          }
        ]
      }
    } else {
      obj = {
        items: [
          {
            key: 'view',
            text: '预览',
            iconProps: {
              iconName: 'View',
            },
            onClick: () => {
              this.handleViewClick(item._id)
            }
          },
          {
            key: 'download',
            text: '插入到word',
            iconProps: {
              iconName: 'Download',
            },
            onClick: () => {
              console.log('插入')
              let html = '<h1>' + item.title + '</h1>' + item.content
              if (this.state.type === '3') {
                html = item.content
              }
              insertHtmlAfterParagraph(html)
              return;
            }
          }
        ]
      }
    }
    return obj
  }

  render() {
    const { currentSort, currentType } = this.state
    const { document = {}, page = 1 } = this.props
    const { rsData = [1, 2], rsCount = 0 } = document

    return (
      <div className='search-document-container'>
        {
          true && (
            <ListContainer
              showContent={rsData.length > 0}
              total={rsCount}
              current={page}
              onPageChange={this.handlePageChange}
              slot={
                <span>
                  <DefaultButton
                    className="order"
                    data-automation-id="test"
                    text={currentType.text}
                    menuProps={
                      {
                        items: typeOptions.map(
                          (item: any) => {
                            return {
                              ...item,
                              onClick: () => {
                                this.onTypeChange(item)
                              }
                            }
                          }
                        )
                      }
                    }
                  />
                  <DefaultButton
                    className="order"
                    data-automation-id="test"
                    // iconProps={{ iconName: 'Down' }}
                    text={currentSort.text}
                    menuProps={
                      {
                        items: sortOptions.map(
                          (item: any) => {
                            return {
                              ...item,
                              onClick: () => {
                                this.onSortChange(item)
                              }
                            }
                          }
                        )
                      }
                    }
                  />
                </span>
              }
            >
              <div className="search-result">
                {
                  rsData.map(
                    item => {
                      return <div onClick={() => this.handleViewClick(item._id)} key={item._id}><ParagraphCard
                        key={item._id}
                        title={item.title}
                        content={item.abs || item.content}
                        menuProps={
                          this.operateMenu(item)
                        }
                      /></div>
                    }
                  )
                }
              </div>
            </ListContainer>
          )
        }

      </div>
    );
  }

  dialog // 赋值打开的弹窗实例

  messageHandler = (arg) => {
    insertHtmlAfterParagraph(arg.message)
    this.dialog.close();
  }

  private handleViewClick = (id): void => {
    // 先点击打开word弹窗
    // 从word弹窗里传的是选择的段落id，通过获取上下文得到相应的 html，再调sdk插入 Word
    const { type } = this.state
    openDialog(`/documentDialog?id=${id}&type=${type}`, this.dialogCallback)
  }

  dialogCallback = (asyncResult) => {
    if (asyncResult.status == "failed") {

      // In addition to general system errors, there are 3 specific errors for
      // displayDialogAsync that you can handle individually.
      switch (asyncResult.error.code) {
        case 12004:
          console.error("Domain is not trusted");
          break;
        case 12005:
          console.error("HTTPS is required");
          break;
        case 12007:
          console.error("A dialog is already opened.");
          break;
        default:
          console.error(asyncResult.error.message);
          break;
      }
    }
    else {
      console.info('弹窗打开成功')
      this.dialog = asyncResult.value;
      /*Messages are sent by developers programatically from the dialog using office.context.ui.messageParent(...)*/
      this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, this.messageHandler);

      /*Events are sent by the platform in response to user actions or errors. For example, the dialog is closed via the 'x' button*/
      this.dialog.addEventHandler(Office.EventType.DialogEventReceived, this.eventHandler);
    }
  }

  eventHandler(arg) {
    // In addition to general system errors, there are 2 specific errors
    // and one event that you can handle individually.
    switch (arg.error) {
      case 12002:
        console.error("Cannot load URL, no such page or bad URL syntax.");
        break;
      case 12003:
        console.error("HTTPS is required.");
        break;
      case 12006:
        // The dialog was closed, typically because the user the pressed X button.
        console.error("Dialog closed by user");
        break;
      default:
        console.error("Undefined error in dialog window");
        break;
    }
  }
}
